<?php

namespace App\Http\Controllers;

use App\Models\Admin;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;

class AgentController extends AdminController
{
    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 我的代理列表页
     */
    public function index(Request $request){

//        DB::listen(function ($sql){
//            dump($sql);
//        });
       $info= $request->user();
        $where=array();
        if(!empty($request->name)){
            $where[]=array("admin.name",'like',"%".$request->name."%");
        }
        if(!empty($request->email)){
            $where[]=array("admin.email",'like',"%".$request->email."%");
        }
        if(!empty($request->phone)){
            $where[]=array("admin.phone",'like',"%".$request->phone."%");
        }
       $list =  Admin::where("sorts",'like','-'.$info->id."%")->where($where)->where("id","!=",$info->id)->where("type",'0')->orderby('id','desc')->paginate(20);
        $append = array();
        $re = $request->toArray();
        foreach ($re as $key => $value) {
            $append[$key] = $value;
        }
        $list->appends($append);
        return view("agent.list",['data'=>$list]);
    }


    public  function array_to_object($arr) {
        if (gettype($arr) != 'array') {
            return;
        }
        foreach ($arr as $k => $v) {
            if (gettype($v) == 'array' || getType($v) == 'object') {
                $arr[$k] = (object)$this->array_to_object($v);
            }
        }

        return (object)$arr;
    }

    /**
     * @param $cate
     * @param int $p_code
     * @param $pname
     * @return array
     * 处理代理人员数组
     */

    public function sortOut($cate,$p_code=0,$pname){
        $tree = array();
        foreach($cate as $key => $v){
            if($v->pid == $p_code){
                $v->pname=$pname;
                $tree[] = $v;
                $tree = array_merge($tree, $this->sortOut($cate,$v->id ,$v->name ));
            }
        }
        return $tree;
    }

    /**
     * 添加代理人员
     */

    public function  create(Request $request){

        if($request->isMethod("POST")){
            $info = $request->user();
            $email=$request->email;
            $ecount = Admin::where("email",$email)->count();
            if($ecount>=1){
                return back()
                    ->withErrors(array("邮箱已经被注册"))
                    ->withInput();
            }elseif($info->percent<$request->percent) {
                return back()
                    ->withErrors(array("提成不能超过上级代理"))
                    ->withInput();
            }else{
            $admin = new Admin();
            $admin->name=trim($request->name);
            $admin->email=$request->email;
            $admin->phone=$request->phone;
            $admin->card=$request->card;
            $admin->code=$this->getcode();
            $admin->password=bcrypt($request->email);
            $admin->pid=$info->id;
            $admin->percent=$request->percent;


            if($admin->save()){
                $admin->sorts=$info->sorts.'-'.$admin->id;
                $admin->save();
                /**
                 * 邮件通知 登录地址和用户名密码
                 */
                $url=$_SERVER["HTTP_HOST"].'/login';
                $content = "恭喜你成为金融代理系统的代理，登录地址：".$url."，用户名:" . $email . "，密码:" . $email;
                Mail::raw($content,function ($message) use($email){
                    $message->subject(config("app.host"));
                    $message->to($email);
                });
                $this->sendsms($request->phone,'SMS_62895109');

                $this->setlog(json_encode($admin),'代理添加下级代理,代理姓名：'.trim($request->name));

                return redirect("/agent");
            }else{
                return back()->withErrors();
            }
            }

//            );

        }else{
            return view("agent.add");
        }

    }

    public function getcode(){
        $pattern='1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
        $key='';
        for($i=0;$i<10;$i++)
        {
            $key .= $pattern{mt_rand(0,35)};    //生成php随机数
        }
        $count= Admin::where("code",$key)->count();
        if($count){
            $key=$this->getcode();
        }
        return $key;
    }

    /**
     * 交易记录
     */
    public function agentlist(Request $request , $id){
        $info = $request->user();
        if($info->id==$id){
            $sort=$info->sorts;
        }else{
            $data = Admin::find($id);
            $sort=$data->sorts;
        }

        $list = User::join("trades","trades.tranid",'=',"users.tranid")->where("sorts","like",$sort."%")->orderby("trades.id","desc")->select("trades.*",'users.firstname','users.sorts','users.lastname','users.email','users.phone')->paginate(6);
//        dd($list);

        foreach ($list as $val){
            $s = Admin::where("sorts",$val->sorts)->first();
            $val->pname= $s->name;
        }
//        dd($list);
        return view("agent.agentlist",['data'=>$list]);
    }
}
